package com.alibaba.hsf.guide.router;

import com.taobao.hsf.annotation.Order;
import com.taobao.hsf.cluster.AbstractSingleTargetRouter;
import com.taobao.hsf.cluster.Router;
import com.taobao.hsf.cluster.RouterFactory;
import com.taobao.hsf.invocation.Invocation;
import com.taobao.hsf.protocol.ServiceURL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * ip最后结尾 奇数 放置在Single-Part-A
 * ip最后结尾 偶数 放置在Single-Part-B
 * </pre>
 *
 * @author weipeng2k 2017年11月25日 下午21:10:55
 */
@Order(2)
public class SingleRouter extends AbstractSingleTargetRouter {

    private Map<String, Router> routerMap = new HashMap<String, Router>();

    @Override
    public Map<String, Router> getSubRouterMap() {
        Map<String, Router> name2Router = new HashMap<String, Router>();
        name2Router.putAll(routerMap);
        return name2Router;
    }

    @Override
    public void setServiceURLs(List<ServiceURL> addresses) {
        super.setServiceURLs(addresses);

        System.out.println(getName() + " accept address: " + addresses);

        List<ServiceURL> oddList = new ArrayList<ServiceURL>();
        List<ServiceURL> evenList = new ArrayList<ServiceURL>();

        for (ServiceURL serviceURL : addresses) {
            if ((serviceURL.getHost().charAt(serviceURL.getHost().length() - 1) - '0') % 2 == 0) {
                evenList.add(serviceURL);
            } else {
                oddList.add(serviceURL);
            }
        }

        Router a = routerMap.get("A");
        System.out.println("notify router " + a.getName() + " address: " + oddList);
        a.setServiceURLs(oddList);

        Router b = routerMap.get("B");
        System.out.println("notify router " + b.getName() + " address: " + evenList);
        b.setServiceURLs(evenList);
    }

    @Override
    public void setRouterFactory(RouterFactory routerFactory) {
        super.setRouterFactory(routerFactory);

        Router partA = routerFactory.createRouter();
        partA.setName("Single-Part-A");
        routerMap.put("A", partA);

        Router partB = routerFactory.createRouter();
        partB.setName("Single-Part-B");
        routerMap.put("B", partB);
    }

    @Override
    protected Router selectRouter(Invocation invocation) {
        String type = (String) invocation.getRequestProp("type");
        Router router = routerMap.get(type);

        return router;
    }
}
